package com.org.redis.lru;

import com.org.redis.config.JedisClient;
import com.org.redis.config.JedisUtils;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * redis实现LRU
 * @author wang
 */
public class LRURedisMap {

    /**
     * 默认LRU缓存长度为4
     */
    static final int DEFAULT_SIZE = 16;

    /**
     * 最多的LRU缓存长度
     */
    static final int MAX_SIZE = 1 << 30;

    /**
     * 自增
     */
    static final String INCR_KEY = "REDIS_MAP";

    /**
     * map名
     */
    static final String DEFAULT_PREFIX = "redis_map_";


    private String mapName;

    /**
     * 缓存长度
     */
    private int capacity;

    /**
     * jedis client
     */
    private static final Jedis jedis = JedisUtils.getJedis();

    /**
     *
     */
    private String[] entry;

    private int dPointer = 0;
    private int aPointer = 0;

    public LRURedisMap(){
        this.mapName = DEFAULT_PREFIX + JedisClient.incr(INCR_KEY);
        this.capacity = DEFAULT_SIZE;
        entry = new String[this.capacity];

    }

    public LRURedisMap(int size,String mapName){
        if(size >= MAX_SIZE){
            this.capacity = MAX_SIZE;
        }else {
            this.capacity = size;
        }
        entry = new String[this.capacity];
        this.mapName = mapName;
    }

//    public void put(String key,String value){
//        if(size() + 1 > this.capacity){
//            jedis.hdel(this.mapName,entry[dPointer]);
//            if( (++dPointer) >= this.capacity){
//                dPointer = 0;
//            }
//        }
////        JedisUtils.setHash(this.mapName,key,value);
//        this.entry[aPointer] = key;
//        if( (++aPointer) >= this.capacity){
//            aPointer = 0;
//        }
//    }

//    public long size(){
//        return JedisUtils.getHLen(this.mapName);
//    }

    public boolean containKey(String key){
        return jedis.hexists(this.mapName,key);
    }

    public boolean containValue(String value){
        Map<String, String> map = jedis.hgetAll(this.mapName);
        for (Map.Entry<String, String> entry : map.entrySet()){
            if(value.equals(entry.getValue())){
                return true;
            }
        }
        return false;
    }

    public void remove(String... key){
        jedis.hdel(this.mapName,key);
    }

}
